ArrayDeque

您所在的位置:网站首页 java arrayqueue ArrayDeque

ArrayDeque

2023-04-17 14:47| 来源: 网络整理| 查看: 265

ArrayDeque

原文见Java 容器源码分析之 Deque 与 ArrayDeque。

概述

ArrayDeque是Deque接口的一个实现,使用了可变数组,所以没有容量上的限制。同时,ArrayDeque是线程不安全的,在没有外部同步的情况下,不能再多线程环境下使用。ArrayDeque是Deque的实现类,可以作为栈来使用,效率高于Stack;也可以作为队列来使用,效率高于LinkedList。需要注意的是,ArrayDeque不支持null值。

结构 //用数组存储元素 transient Object[] elements; // non-private to simplify nested class access //头部元素的索引 transient int head; //尾部下一个将要被加入的元素的索引 transient int tail; //最小容量,必须为2的幂次方 private static final int MIN_INITIAL_CAPACITY = 8;

在ArrayDeque底层使用了数组来存储数据,同时用两个int值head和tail来表示头部和尾部。不过需要注意的是tail并不是尾部元素的索引,而是尾部元素的下一位,即下一个将要被加入的元素的索引。

初始化

ArrayDeque有三个构造函数来初始化,除了无参的构造函数使用了默认容量,其它两个构造函数会通过allocateElements来计算初始容量。

public ArrayDeque() { elements = new Object[16]; } public ArrayDeque(int numElements) { allocateElements(numElements); } public ArrayDeque(Collection


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3